<template>
  <p class="my-5 px-2 text-base font-[600] lg:mb-8 lg:mt-10 lg:text-2xl uppercase">
    {{ $mt('Checkout') }}
  </p>

  <div class="lg:flex lg:items-start lg:justify-between">
    <!--    左侧-->
    <section class="flex-1 lg:ltr:mr-6 lg:rtl:ml-6">
      <div class="mb-5 rounded-md bg-[#22282a] px-5 py-2.5">
        <h5 class="mb-5 mt-3.5 border-b-[.5px] border-b-[#505355b5] pb-3.5 lg:mb-8 lg:mt-5 lg:pb-5">
          {{ curGoodsDetail.name }}
        </h5>
        <div class="mb-2.5 flex items-center justify-between lg:mb-6">
          <NuxtLink
            external
            class="flex items-center flex-1 cursor-pointer"
            :to="$localePath(`/goods/${curGoodsDetail.urlName || curGoodsDetail.id}`)">
            <y-image
              class="ltr:mr-2.5 rtl:ml-2.5 object-cover product-poster--small w-16 h-16 shrink-0 rounded-md"
              :src="curGoodsSkuInfo.smallIcon || curGoodsDetail.imageUrl"
              :alt="curGoodsSkuInfo.name"
              width="70" />
            <div>
              <p class="break-all font-bold">
                {{ curGoodsDetail.isWalletPurchaseGoods ? $calcPrice(curGoodsSkuInfo.price) : curGoodsSkuInfo.name }}
              </p>
              <p class="text-gray mt-1">{{ curGoodsDetail.areaCode }}</p>
            </div>
          </NuxtLink>
          <div
            v-if="!(curGoodsSkuInfo.minLimit === 1 && curGoodsSkuInfo.maxLimit === 1)"
            class="lg:flex-row flex-col justify-center ml-1 items-center shrink-0 w-30 lg:w-[120px] break-all lg:justify-between lg:pr-5">
            <van-stepper
              :min="curGoodsSkuInfo.minLimit ? curGoodsSkuInfo.minLimit : 1"
              :max="curGoodsSkuInfo.maxLimit ? curGoodsSkuInfo.maxLimit : 10000"
              integer
              class="mb-2 shrink-0 lg:mb-0"
              v-model="count" />
            <p class="font-[600] text-center text-red1 whitespace-nowrap mt-2">
              {{ $calcPrice(count * curGoodsSkuInfo.price) }}
            </p>
          </div>
        </div>
      </div>
      <!--        左侧2-->
      <div class="mb-5 rounded-md bg-[#30383b78] px-5 py-3 min-h-12">
        <h3 class="text-base hairline-bottom pb-3 mb-4 flex items-center">
          <span>{{ $mt('Payment Method') }}</span>
          <van-loading size="20" class="ml-3" v-if="loading" />
        </h3>
        <template v-if="paymentList.length">
          <section class="grid grid-cols-2 lg:flex pb-2 flex-wrap lg:-ml-4">
            <div
              @click="handleClickPayment(item)"
              :class="curPaymentId === +item.id ? 'border-red1 select-payment' : 'border-transparent'"
              class="mt-2 lg:ml-4 shrink-0 w-fit min-w-[140px] h-14 px-2 py-1 lg:hover:border-red1 duration-75 rounded-sm cursor-pointer border"
              v-for="item in paymentList">
              <y-image
                :src="item.imageUrl"
                :alt="item.name"
                height="40"
                class="h-10 rounded-md mx-auto object-contain object-center"
                placeholder />
            </div>
          </section>
          <p
            v-if="
              (langCookie?.includes?.('zh') || curCurrency.currencyCode === 'HKD') && curCurrency.currencyCode !== 'CNY'
            ">
            注意：中国大陆用户请点击右上角 将货币(例如：
            <nuxt-link
              external
              :to="$localePath(`/common/lang?redirectTo=${encodeURIComponent(route.fullPath)}`)"
              class="font-bold underline">
              美元
            </nuxt-link>
            ) 切换成
            <nuxt-link
              external
              :to="$localePath(`/common/lang?redirectTo=${encodeURIComponent(route.fullPath)}`)"
              class="font-bold underline">
              人民币
            </nuxt-link>
            进行下单支付
          </p>
        </template>
        <van-empty
          v-else
          :description="$mt('No payment method for current IP or currency. Switch to local currency or USD.')" />
      </div>
      <!--      左侧3-->
      <div class="mb-5 rounded-2xl bg-[#30383b78] px-5 py-3 pb-6 min-h-12">
        <h3 class="text-base items-center hairline-bottom pb-3 mb-4 flex justify-between">
          {{ $mt('Recharge information') }}
          <span v-if="curPaymentObj?.paymentCode === 'BIT_WALLET'" class="text-xs">
            {{ $mt('Balance') }} {{ $calcPrice(memberInfo.balanceForUSD) }}
          </span>
        </h3>
        <section class="grid grid-cols-1 gap-y-3">
          <div v-for="item in rechargePlatformConfig">
            <p class="mb-2 ml-0.5 text-white1">{{ item.name }}</p>
            <select
              v-if="item.selected"
              v-model="item.value"
              class="select rounded-sm bg-black select-sm select-info w-3/5 max-w-xs"
              :class="{ 'select-error': !item.value }">
              <option disabled selected :value="null">{{ item.tip }}</option>
              <option :value="sub" v-for="sub in item.values">{{ sub.name }}</option>
            </select>
            <input
              v-else
              type="text"
              autocomplete="off"
              name="uniqueName2"
              id="uniqueId2"
              v-model.trim="item.value"
              :placeholder="item.tip"
              class="input rounded-sm bg-black input-sm input-bordered input-info w-full max-w-xs"
              :class="{ 'select-error': !item.value }" />
          </div>
          <div>
            <p class="mb-2 ml-0.5 text-white1">{{ $mt('Contact Email') }}</p>
            <input
              type="text"
              v-model.trim="userEmail"
              autocomplete="off"
              name="uniqueName1"
              id="uniqueId1"
              ref="emailEl"
              :placeholder="$mt('Please Enter Email')"
              :class="{ 'select-error': !userEmail }"
              class="input rounded-sm bg-black input-sm input-bordered input-info w-full max-w-xs" />
          </div>
          <div v-if="curGoodsDetail.isWalletPurchaseGoods || curPaymentObj?.paymentCode === 'BIT_WALLET'">
            <p class="mb-2 ml-0.5 text-white1">{{ $mt('Password') }}</p>
            <input
              type="text"
              v-model.trim="userPassword"
              autocomplete="off"
              name="uniqueName2"
              ref="passwordEl"
              id="uniqueId2"
              :placeholder="$mt('Please Enter Password')"
              :class="{ 'select-error': !userPassword }"
              class="input rounded-sm bg-black input-sm input-bordered input-info w-full max-w-xs" />
            <p class="mt-2 text-white3">
              <span>{{ $mt('If you forgot your password or never set one') }},</span>
              <span class="link-info underline cursor-pointer" @click="changePassEl.showDialog()">
                {{ $mt('click here to reset your password') }}
              </span>
              <span>.</span>
              <span>{{ $mt('If your wallet balance is not enough, please top up your wallet in the') }},</span>
              <span class="link-info underline cursor-pointer" @click="$pushRoute('/user')">
                {{ $mt('User Profile Page') }}
              </span>
              <span>.</span>
            </p>
          </div>
        </section>
      </div>
    </section>
    <!--   右侧-->
    <section class="w-full lg:w-[35%]">
      <!--            右1-->
      <div class="mb-5 rounded-md bg-[#30383b] px-5 py-4 lg:py-5">
        <p class="mb-5 border-b-[.5px] border-b-[#505355b5] pb-3.5 lg:pb-5">
          {{ $mt('Payment Details') }}
        </p>
        <div class="mb-2.5 flex items-center justify-between">
          <p>{{ $mt('Original Price') }}</p>
          <p class="line-through text-gray-light">
            {{ $withCurrencySymbol(totalOriginalGoodsPriceWithCurrency) }}
          </p>
        </div>
        <div v-if="curGoodsSkuInfo.discount" class="mb-2.5 flex items-center justify-between">
          <p>{{ $mt('Limited Time Discount') }}</p>
          <p class="text-[#9acd32]">{{ curGoodsSkuInfo.discount }}% OFF</p>
        </div>
        <div class="mb-2.5 flex items-center justify-between">
          <p>{{ $mt('Discounted Price') }}</p>
          <p class="text-[#9acd32]">≈ {{ $withCurrencySymbol(totalAmountDiscount) }}</p>
        </div>
        <div class="mb-2.5 flex items-center justify-between">
          <p>{{ $mt('Payment Method Fee') }}</p>
          <p>
            {{ ((totalAmountFee / totalAmount) * 100).toFixed(2) }}% ( ≈ {{ $withCurrencySymbol(totalAmountFee) }} )
          </p>
        </div>
      </div>

      <!--右2-->
      <div class="rounded-md bg-[#30383b] px-5 py-3.5 lg:py-5">
        <section class="flex pl-1 items-center justify-between">
          <div>
            <p class="text-base font-[700] text-red1 mb-1 lg:mb-2">{{ $withCurrencySymbol(totalAmount) }}</p>
            <p class="text-xs text-[#878d8f]">{{ $mt('Final Payment Amount') }}</p>
          </div>
          <button
            name="button"
            @click="submitHandle"
            class="flex items-center justify-center rounded-3xl bg-red1 min-w-[120px] ml-2 lg:min-w-[140px] px-2 py-3 text-sm font-[700]">
            <span>{{ $mt('PAY NOW') }}</span>
          </button>
        </section>
      </div>
    </section>
  </div>
  <van-dialog
    @confirm="createOrder()"
    v-model:show="isShowAgainConfirmInfo"
    :title="$mt('Please Confirm Your Information')"
    :cancelButtonText="$mt('Cancel')"
    :confirmButtonText="$mt('Confirm')"
    show-cancel-button>
    <div class="p-4 px-8 min-h-16">
      <div class="mb-3 last:mb-0 text-center flex">
        <div class="mr-2 whitespace-nowrap">{{ $mt('Email') }}</div>
        <span class="text-[#08e308] ml-auto break-words flex-1 overflow-hidden text-right">{{ userEmail }}</span>
      </div>
      <div
        v-if="curGoodsDetail.isWalletPurchaseGoods || curPaymentObj?.paymentCode === 'BIT_WALLET'"
        class="mb-3 last:mb-0 text-center flex">
        <div class="mr-2 whitespace-nowrap">{{ $mt('Password') }}</div>
        <span class="text-[#08e308] ml-auto break-words flex-1 overflow-hidden text-right">{{ userPassword }}</span>
      </div>
      <div v-for="item in rechargePlatformConfig" class="mb-2 text-center last:mb-0 flex">
        <div class="mr-3 whitespace-nowrap">{{ item.name }}</div>
        <span class="text-[#08e308] ml-auto break-words flex-1 overflow-hidden text-right">
          {{ item.selected ? item.value.name : item.value }}
        </span>
      </div>
      <template v-if="curPayment?.paymentCode === 'GATE_IO_PAY' || curPayment?.paymentCode === 'BUFF_PAY'">
        <p class="mt-3 mb-1 text-red-400">{{ $mt('Note: Please Read Below!') }}</p>
        <p class="text-xs text-red-100">
          {{
            $mt(
              'This payment only supports Tether USDT currency. Do not send other currencies, such as ETH, BTC, BNB, or others. Please make sure you have enough Tether USDT currency!',
            )
          }}
        </p>
      </template>
    </div>
  </van-dialog>
  <LoginChangePassDialog @pwdChange="($event) => (userPassword = $event)" ref="changePassEl" />
  <van-dialog
    v-model:show="isShowQRCodeDialog"
    :title="$mt('Please scan the QR code to pay')"
    :confirmButtonText="$mt('Confirm')"
    :show-cancel-button="false">
    <vue-qrcode :value="qrCodeStr" />
  </van-dialog>
</template>

<script setup lang="ts">
import YImage from '~/components/logic/YImage.vue'
import { useMetaStore } from '~/store/meta'
import { useMemberStore } from '~/store/member'
import { useRouteQuery } from '@vueuse/router'
import { fuckRequestParams, isMobile, safeJsonParse, setBitId } from '~/utils'
import dayjs from 'dayjs'
import VueQrcode from 'vue-qrcode'

useSeoMeta({ title: 'BitTopup - Order Checkout' })
const isShowQRCodeDialog = ref(false)
const qrCodeStr = ref('')
const isShowAgainConfirmInfo = ref(false)
const langCookie = useCookie('i18n_redirected', { path: '/', default: () => 'en' })
const commonApi = useCommonPlugin()
const { $mt, $payWithOrderInfo, $withCurrencySymbol, gtag_report, $getExchangePrice, $multiplyWithRate } = commonApi
const curPaymentId = ref(null)
const loading = ref(true)
const metaStore = useMetaStore()
const memberStore = useMemberStore()
const route = useRoute()
const userEmail = useLocalStorage('userEmail', memberStore.memberInfo.email || '')
const userPassword = useLocalStorage('userPassword', '')
const emailEl = ref<HTMLElement>()
const passwordEl = ref<HTMLElement>()
const changePassEl = ref()
const curPaymentObj = ref({} as any)
const { goodsSkuId } = useRoute().query
const { memberInfo } = storeToRefs(memberStore)
// 选择支付方式
const handleClickPayment = (item) => {
  curPaymentObj.value = item
  curPaymentId.value = item.id
  setTimeout(() => gtag_report('conversion_event_default_2'), 300)
}
const curPayment = computed(() => metaStore.paymentList.find((item) => item.id === curPaymentId.value) ?? {})
const {
  curGoodsSkuInfo = {},
  curGoodsDetail = {},
  rechargePlatformConfig: cachedRechargePlatformConfig,
} = useLocalStorage<any>(`PreOrderCacheNew-${goodsSkuId}`, {}).value
onMounted(async () => {
  if (curGoodsSkuInfo.id) return
  await showConfirmDialog({
    message: $mt('Parameters are missing, please go to the product page to place the order again.'),
    confirmButtonText: $mt('Confirm'),
    showCancelButton: false,
  })
  commonApi.$forceReplaceRoute(commonApi.$localePath('/'))
})
let platformConfig = curGoodsDetail?.platformConfig
try {
  platformConfig = typeof platformConfig === 'string' ? JSON.parse(platformConfig) : platformConfig || []
} catch (e) {}
const rechargePlatformConfig = ref((cachedRechargePlatformConfig || platformConfig) ?? [])
const { paymentList, curCurrency } = storeToRefs(metaStore)
watch(
  () => paymentList.value,
  () => {
    curPaymentId.value ||= paymentList.value[0]?.id
  },
)
const totalOriginalGoodsPriceWithCurrency = computed(() => {
  let totalPrice = +count.value * curGoodsSkuInfo.originalPrice
  return $getExchangePrice(totalPrice)
})
const totalGoodsPriceWithCurrency = computed(() => {
  let totalPrice = +count.value * curGoodsSkuInfo.price
  return $getExchangePrice(totalPrice)
})
const totalAmount = computed(() => {
  const padZeroForTotalAmount = (num) => (curCurrency.value.allowDecimal ? num : Math.ceil(num))
  let totalPrice = totalGoodsPriceWithCurrency.value
  if (metaStore?.channelData?.upRate) totalPrice *= metaStore.channelData.upRate
  return padZeroForTotalAmount($multiplyWithRate(totalPrice, curPayment.value.feeRate))
})
const totalAmountDiscount = computed(
  () => totalOriginalGoodsPriceWithCurrency.value - totalGoodsPriceWithCurrency.value,
)
const totalAmountFee = computed(() => totalAmount.value - totalGoodsPriceWithCurrency.value)
const count = useRouteQuery('count')
const { requestPostNew } = useRequest()
const { $pushRoute, $localePath } = useCommonPlugin()
metaStore.initPaymentList(goodsSkuId).finally(() => (loading.value = false))
const submitHandle = async () => {
  if (!userEmail.value) {
    await showConfirmDialog({
      title: $mt('Notice'),
      message: $mt('Please enter your email first !'),
      showCancelButton: false,
      confirmButtonText: 'OK',
    })
    emailEl?.value.focus()
    emailEl?.value.scrollIntoView({ block: 'center', behavior: 'smooth' })
    return
  }
  if (
    (curGoodsDetail.isWalletPurchaseGoods || curPaymentObj.value?.paymentCode === 'BIT_WALLET') &&
    !userPassword.value
  ) {
    await showConfirmDialog({
      title: $mt('Notice'),
      message: $mt('Please enter your password first !'),
      showCancelButton: false,
      confirmButtonText: 'OK',
    })
    passwordEl?.value.focus()
    passwordEl?.value.scrollIntoView({ block: 'center', behavior: 'smooth' })
    return
  }
  if (!curPaymentId.value) return showToast($mt('Please chose a payment method !'))
  if (curPayment.value.notSupportIp)
    return showConfirmDialog({
      title: $mt('Notice'),
      showCancelButton: false,
      confirmButtonText: 'OK',
      message: `${$mt('The IP required for this payment method is')}: ${curPayment.value.areaCode} , ${$mt(
        'But your ip is',
      )}: ${curPayment.value.country} , ${$mt('So your IP does not support this payment method.')}`,
    })
  if (rechargePlatformConfig.value.some((item) => !item.value))
    return showToast($mt('Please fill in the recharge information'))
  isShowAgainConfirmInfo.value = true
}
const createOrder = async () => {
  showLoadingToast({ message: $mt('Creating order'), duration: 0, forbidClick: true })
  const orderParams = {
    email: userEmail.value,
    successCallBackUrl: `${location.origin}${$localePath('/user/order')}`,
    goodsSkuId,
    count: count.value,
    password: userPassword.value,
    endType: isMobile() ? 1 : 0,
    rechargeFormList: rechargePlatformConfig.value.map((item) => ({ ...item, values: undefined })),
    currencyId: curCurrency.value.id,
    paymentId: curPaymentId.value,
    timeStamp: dayjs().valueOf(),
  }
  const fuckHeaders = fuckRequestParams(orderParams)
  try {
    await setBitId()
    const { token, ...orderInfo } = await requestPostNew('/app/order/createAndRegister', orderParams, {
      withAuth: true,
      hideError: true,
      headers: fuckHeaders,
    })
    localStorage.setItem('authToken', token)
    memberStore.updateMemberProfile()
    const res = $payWithOrderInfo({
      orderInfo,
      showReport: true,
      showQRCode: true,
      paymentData: curPayment.value,
    })
    if (res?.type === 'SHOW_QR_CODE') {
      closeToast(true)
      isShowQRCodeDialog.value = true
      qrCodeStr.value = res.pcPayPath
    }
  } catch (e) {
    closeToast(true)
    await showConfirmDialog({
      showCancelButton: false,
      message: e.message,
      confirmButtonText: 'Confirm',
    })
  }
}
</script>

<style scoped lang="scss">
.select-payment {
  position: relative;

  &:after {
    position: absolute;
    left: -7px;
    top: -7px;
    content: '';
    border: 7px solid transparent;
    border-right-color: #eb414e;
    transform: rotateZ(45deg);
  }
}

:deep(.van-cell) {
  background-color: unset;
  color: #fff;
}

:deep(.van-field__label) {
  color: #fff;
  font-size: 12px;
}

:deep(.van-field__control::placeholder) {
  font-size: 12px;
}

:deep(.van-field__control) {
  color: #fff;
}
</style>
